package com.allinpay.merchantweb.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.allinpay.merchantweb.common.utils.StringUtil;
import com.allinpay.merchantweb.constants.CommonConstants;
import com.allinpay.merchantweb.model.CommRoleInfo;
import com.allinpay.merchantweb.model.CommRolePrivilege;
import com.allinpay.merchantweb.model.EnterpriseInfo;
import com.allinpay.merchantweb.model.EnterpriseProdAduitInfo;
import com.allinpay.merchantweb.model.EnterpriseProdInfo;
import com.allinpay.merchantweb.model.EnterpriseProdInfoVo;
import com.allinpay.merchantweb.model.FinancialProdInfo;
import com.allinpay.merchantweb.model.FinancialProdInfoVo;
import com.allinpay.merchantweb.model.Manager;
import com.allinpay.merchantweb.model.PageForLayui;
import com.allinpay.merchantweb.response.ResponseData;
import com.allinpay.merchantweb.service.IAllinpayProductionService;
import com.allinpay.merchantweb.service.IProductionService;
import com.google.gson.Gson;

/**
 * 处理文件controller
 * @author dell
 *
 */
@Controller
@RequestMapping(value="file")
public class FileController {
	
	private final static  Logger log = LoggerFactory.getLogger(FileController.class);
	
	String prefix = "trade/file";
	
	
	@Autowired
	IAllinpayProductionService productionService;

	@RequestMapping("batchAddEmployee")
	String batchAddEmployee() {
		return prefix + "/batchAddEmployee";
	}
	

	
	@RequestMapping(value="addProd")
	String addProd() {
		return prefix + "/addAllinpayProd";
	}
	
	/**
     * 实现多文件上传
     * */
    @RequestMapping(value="multifileUpload",method=RequestMethod.POST) 
	/**public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files) */
    public @ResponseBody String multifileUpload(HttpServletRequest request){
        
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
        
        if(files.isEmpty()){
            return "false";
        }

        String path = "F:/test" ;
        
        for(MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);
            
            if(file.isEmpty()){
                return "false";
            }else{        
                File dest = new File(path + "/" + fileName);
                if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                }catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return "false";
                } 
            }
            break;
        }
        return "true";
    }
	
	/**
	 * 查询产品列表
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping(value="queryFinancialProds")
	@ResponseBody
	public Object queryFinancialProds(HttpServletRequest httpRequest) {
		Object retObject = null;
		FinancialProdInfo financialProdInfo = new FinancialProdInfo();
		//only for testing Code

		String sPageNum = httpRequest.getParameter("page");
		String sPageSize = httpRequest.getParameter("limit");

		try {
			Map<String, Object>  reqMap = new HashMap<String, Object>();
			if ( !StringUtil.isEmpty(sPageSize) ) {
				financialProdInfo.setNumPerPage( Integer.parseInt(sPageSize));
			}
			if ( !StringUtil.isEmpty(sPageNum) ) {
				financialProdInfo.setPageNum( Integer.parseInt(sPageNum));
			}	
			
			// enterpriseProdInfo.setProdClass(2);//只查询定期产品
			ResponseData<FinancialProdInfoVo> respBean = productionService.queryFinancialProds(financialProdInfo);
			PageForLayui page = new PageForLayui();
			page.setCode("0");
			page.setMsg("succ");
			page.setCount(respBean.getTotal());
			page.setData(respBean.getDataList());
			
			retObject = page;
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retObject;
	}
	
	
	@RequestMapping(value="/addFinancialProd")
	@ResponseBody
	public Object addFinancialProd(FinancialProdInfo prodInfo) {
		

		Object retObject = null;
		try {
			System.out.println("ready to addFinancialProd");
			retObject = productionService.addFinancialProd(prodInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("ready to return new Object");
			return new PageForLayui("110", e.getMessage() );
		}
		
		return retObject;
	}
	
	
	
	@RequestMapping(value="/updateFinancialProd")
	@ResponseBody
	public Object updateFinancialProd(  HttpServletRequest request) {

		byte[] bytes = new byte[0];
		ServletInputStream inputStream;
		try {
			inputStream = request.getInputStream();
			bytes = new byte[inputStream.available()];
			inputStream.read(bytes);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		Map<String, String[]> map = request.getParameterMap();
		
		String str = new String(bytes);
		System.out.println("updateEnterpriseProd commRoleInfo len:" +
				request.getContentLength()
				);
		System.out.println("updateEnterpriseProd map:" +
				new Gson().toJson(map)
				);
		
		String prodId = request.getParameter("prodId");
		String prodRate = request.getParameter("prodRate");
		String prodAlterRate = request.getParameter("prodAlterRate");
		String prodRaiseLimit = request.getParameter("prodRaiseLimit");
		String prodBuyMinmonye = request.getParameter("prodBuyMinmonye");
		String showPriority = request.getParameter("showPriority");
		
		Object retObject = null;
		try {
			FinancialProdInfo prodInfo = new FinancialProdInfo();
			
			if( !StringUtil.isEmpty(prodId) ) {
				prodInfo.setProdId(Integer.parseInt(prodId));
			}else {
				return new Object() {String code="110"; String msg="prodId is null";};
			}
			
			if( !StringUtil.isEmpty(prodRate) ) {
				prodInfo.setProdRate(prodRate+"%");
			}
			
			if( !StringUtil.isEmpty(prodAlterRate) ) {
				prodInfo.setProdRate(prodAlterRate+"%");
			}
			
			if( !StringUtil.isEmpty(prodRaiseLimit) ) {
				prodInfo.setProdRaiseLimit(BigDecimal.valueOf(Double.parseDouble(prodRaiseLimit) ) );
			}
			
			if( !StringUtil.isEmpty(prodBuyMinmonye) ) {
				prodInfo.setProdBuyMinmonye((int)(Double.parseDouble(prodBuyMinmonye) ) );
			}
			
			
			
			Manager manager = (Manager) request.getSession(false).getAttribute(CommonConstants.SESSIONMANAGER);
			
			productionService.updateFinancialProd(prodInfo
					, manager.getInstanceId(), manager.getUserAccount());
			PageForLayui page = new PageForLayui();
			page.setCode("0");
			page.setMsg("succ");
			retObject = page;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new PageForLayui("110", e.getMessage() );
		}
		
		return retObject;
	}
	
	
	
}
